<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019\3\7 0007
 * Time: 14:26
 */

namespace app\admin\controller;

use app\service\apixcxService;
use app\service\billService;
use app\service\homeService;
use app\service\repairService;
use app\service\xcxService;
use printing\printDemo;
use think\Controller;
use think\facade\Db;
use think\facade\Log;

class Xcx extends Controller
{
    public function test(){
        $data=request()->get();
        Log::write($data,"test");
    }
    public function ewm(){
        $url_param="pages/PropertyPayCost/selectRoom/selectRoom";
        $query_param="query=ANV4NOXUY3301";
        $describe="This is a applet QR code";
        $api = new apixcxService();
        $result=$api->qrcodeCreate(json_encode(['url_param'=> $url_param,'query_param'=>$query_param,'describe'=>$describe]));
        var_dump($result);

    }
    
    public function bindcommunity()
    {
        $data["community_id"]=request()->get("community_id");
        $data["user_id"]=request()->get("user_id");
        $data["community_name"]=request()->get("community_name");
        $applet_user=Db::table("applet_community")
                        ->where("user_id", $data["user_id"])
                        ->find();
        if(!empty($applet_user))
        {
            Db::table("applet_community")->update($data);
            return json_encode(["errcode"=>"0"]);
        }else
        {
            $data["create_time"]=time();
            Db::table("applet_community")->insert($data);
            return json_encode(["errcode"=>"0"]);
        }
    }

    public function user_community()
    {
        $user_id=request()->get("user_id");
        $user_community=Db::table("applet_community")
                        ->where("user_id", $user_id)
                        ->find();
        if(!empty($user_community))
        {
            return json_encode(["errcode"=>"0","city"=>$user_community["community_name"],"community_id"=>$user_community["community_id"]]);
        }else
        {
            return json_encode(["errcode"=>"1"]);
        }
    }

    public function formIdAdd(){
        $applet_form["ctime"]=time();
        $applet_form["user_id"]=request()->get("user_id");
        $applet_form["form_id"]=request()->get("formId");
        $applet_form["num"]=3;
        //$res=Db::table("applet_form")->insert($applet_form);
    }
    public function getcommunityinfo(){
        $community_id=request()->get("community_id");
        //Log::write(request()->param(),"communityinfo");
        Db::name('test')->insert(['test'=>$community_id]);
        if(empty($community_id)){
             return json_encode(["error"=>"1"]);
        }
        
        
        $communityinfo=Db::table("community")->where("community_id",$community_id)->find();
        if(empty($communityinfo)){
            return json_encode(["error"=>"1"]);
        }else{

            return json_encode($communityinfo);
        }
        
    }
    //小区列表
    public function  village(){
        if(isset($_GET['communityname'])){
            $communityname = $_GET['communityname'];
            $li = (new xcxService())->communityName($communityname);

            foreach ($li as $l){
                $lis['adcode'] = $l['community_id'];
    			$lis['address'] = $l['community_address'];
                $lis['city'] = $l['community_name'];
                $list[] = $lis;
            }
        }else{
            $li = (new xcxService())->communityList();
            //echo "<pre>";
            //var_dump($li);die;
            foreach ($li as $l){
                $lis['adcode'] = $l['community_id'];
    			$lis['address'] = $l['community_address'];
                $lis['city'] = $l['community_name'];
                $list[] = $lis;
            }
        }
        if(empty($list)){
            return json_encode($li);
        }else{
            return json_encode($list);
        }
    }

    //组团列表
    public function group(){
        $community_id = $_GET['adcode'];
       
        $t = (new xcxService())->groupList($community_id);
          $list = array_unique($t);
		$list = json_encode(implode(",",$list));
		$list = json_decode($list,true);
		$list =explode(",",$list); 
        return json_encode($list);
    }
    //幢数列表
    public function building()
    {
		$community_id = $_GET['adcode'];
        $building = $_GET['group'];
        $t = (new xcxService())->buildingList($building,$community_id);

		$list = array_unique($t);
		$list = json_encode(implode(",",$list));
		$list = json_decode($list,true);
		$list =explode(",",$list); 
        //var_dump($list);
		//asort($list,SORT_NATURAL|SORT_STRING|SORT_FLAG_CASE);
        sort($list,SORT_NATURAL|SORT_STRING|SORT_FLAG_CASE);
        //var_dump($list);
        return json_encode($list);
    }
    //单元列表
    public function unit()
    {
		$community_id = $_GET['adcode'];
        $building = $_GET['group'];
        $unit = $_GET['building'];
        $t = (new xcxService())->unitList($unit,$building,$community_id);
        $list = json_encode(implode(",",$t));
		$list = json_decode($list,true);
		$list =explode(",",$list); 
		sort($list,SORT_NATURAL|SORT_STRING|SORT_FLAG_CASE);
        return json_encode($list);
    }
    //房屋列表
    public function room()
    {
		$community_id = $_GET['adcode'];
        $building = $_GET['group'];
        $unit = $_GET['building'];
        $room = $_GET['unit'];
        $t = (new xcxService())->roomList($room,$unit,$building,$community_id);
         $list = json_encode(implode(",",$t));
		$list = json_decode($list,true);
		$list =explode(",",$list); 
		sort($list,SORT_NATURAL|SORT_STRING|SORT_FLAG_CASE);
        return json_encode($list);
    }
    //提交信息计算物业费
    public function details()
    {
        //根据小区和完整门牌号查询房屋信息
        $roominfo = (new xcxService())->getroominfo($_GET['adcode'],$_GET['group'],$_GET['building'],$_GET['unit'],$_GET['room']);
		
        //根据房号查询账单
        $billlis = (new xcxService())->billRoomIdList($roominfo['out_room_id']);
		$billlist = (new xcxService())->cost_type($roominfo['out_room_id']);
		 
        foreach ($billlist as $b){
            $lis[] = (new xcxService())->cost_type_bill($roominfo['out_room_id'],$b);
        }
		//$lis = array_unique($lis);
        foreach($billlis as $list){
            $info['acct_period'][] = $list['acct_period'];
            $info['cost_type'][] = $list['cost_type'];
            $info['bill_amount'][] = $list['bill_entry_amount'];
            $info['id'][] = $list['id'];
        }
        if(empty($info)){
            return json(['error' => '暂无可缴费账单']);
        }
        return json_encode($lis);

    }

    //账单信息确认
    public function billconfirm(){
        $trade_no=request()->post("trade_no");
        $orderinfo=Db::table("billpay")->where("trade_no",$trade_no)->find();
        $roominfo=Db::table("roominfo")->where("out_room_id",$orderinfo["out_room_id"])->find();
        $orderinfo["owner_name"]=$roominfo["owner_name"];
        return json_encode($orderinfo);
    }
    //确认订单
    public function order(){
        $data=request()->post();
        $user_id =  $data['user_id'];
        $id = $data['id'];

        if(empty($id)){
            return json(['errorCode'=>'1','error' => '请选择要缴费的账单']);
        }

		//$id = array_unique($data['id']);
        //根据账单编号查询账单金额
        $infolist = (new billService())->billEntryIdInfo($id);
        
        if(count($infolist) != count($id)){
            return json(['errorCode'=>'1','info' => '账单信息不完整']);
        }

        $out_room_id="";
        $room_address="";
        $community_id="";
        foreach($infolist as $info){
            //查询小区名称
            $community_name = (new billService())->communityMachine($info['community_id'])['community_name'];
            $bill_entry_amount[] = $info['bill_entry_amount'];
            $out_room_id = $info['out_room_id'];
            $community_id = $info['community_id'];
            $room_address = $info['room_address'];
        }

        $out_trade_no = time().rand(100000,999999);
        $bill_amount_sum = array_sum($bill_entry_amount);
        
        $roominfo=Db::table("roominfo")->where("out_room_id",$out_room_id)->find();
        $subject = $community_name.$room_address.'-'.$roominfo["owner_name"].'物业缴费';
         
        //查询token
        $token = (new xcxService())->token($community_id);
        //Log::write($token,"token");
        $api = new apixcxService();
        $notifyUrl="https://www.jfzhiwen.com/admin/callback/alinotice";
        $result = $api->create(json_encode(['out_trade_no'=> $out_trade_no,'total_amount'=>$bill_amount_sum,'buyer_id'=>$user_id,'subject' =>$subject,'token'=>$token ,'notifyUrl'=>$notifyUrl]));
        //Log::write($result,"订单信息");
        if(property_exists($result,'sub_msg')){
            return json(['errorCode'=>'1','info' => $result->sub_msg]);
        }else{
			$close_id = $id['0'];
            $is_trade_no = Db::name('bill')->where('id',$close_id)->value('trade_no');
            if(!empty($is_trade_no)){
                
				$aaa = $api->close(json_encode(['trade_no' => $is_trade_no,'token' => $token]));
				if(property_exists($aaa,'sub_msg')){
                   Db::name('test')->insert(['test'=>$aaa->sub_msg]);
				   Db::name('test')->insert(['test'=>$is_trade_no]);
				}
				
            }
            //添加进数据库
            $bill['trade_no'] =  $result->trade_no;
            $bill['out_trade_no'] = $out_trade_no;
            $bill['user_id'] = $user_id;
            foreach($id as $billid){
                $bill['id'] = $billid;
                $billedit = (new billService())->billEdit($bill);
                if(empty($billedit)){
                    return json(['errorCode'=>'1','info' => '账单存储失败']);
                }
            }
            $billpay["user_id"]=$user_id;
            $billpay["order_money"]=$bill_amount_sum;
            $billpay["pay_money"]=$bill_amount_sum;
            $billpay["out_trade_no"]= $out_trade_no;
            $billpay["trade_no"]= $bill['trade_no'];
            $billpay["billid"]=serialize($id);
            $billpay["out_room_id"]=$out_room_id;
            $billpay["room_address"]=$room_address;
            $billpay["community_name"]=$community_name;
            $billpay["community_id"]=$community_id;
            $billpay["scenes"]=2;
            $res=Db::table("billpay")->insert($billpay);
            if($res){
                //返回结果到前台唤起收银台
                return json(['trade_no' => $bill['trade_no']]);
            }else{
                return json(['errorCode'=>'1','info' => '账单存储失败']);
            }
            
        }
    }

    


	 //获取支付宝用户的user_id
    public function userId()
    {
        $api = new apixcxService();
        //获取当前车辆支付宝ID
        $code = request()->get('auth_code');
        $oauthtoken = $api->xcxoauthToken($code);
        if(property_exists($oauthtoken,'sub_msg')){
            return json(['info' => $oauthtoken->sub_msg]);
        }
        $user_id = $oauthtoken->user_id;//user_id
        return json(['info' => $user_id]);
        return json_encode($user_id);
    }
	 //个人保修类型
    public function person()
    {
        $repairType = (new xcxService())->typeList();
        return json_encode($repairType);
    }
	//将对象转化成数组
	//调用这个函数，将其幻化为数组，然后取出对应值
	public function object_array($array)
	{
	   if(is_object($array))
	   {
		$array = (array)$array;
	   }
	   if(is_array($array))
	   {
		foreach($array as $key=>$value)
		{
		 $array[$key] = object_array($value);
		}
	   }
	   return $array;
	}
	 //用户保修记录
    public function lists()
    {
        $user_id = $_GET['user_id'];
		
        $list = (new xcxService())->repairslist($user_id);
		if($list){
			foreach($list as $l){
			$type['name'] = (new xcxService())->repairsName($l['repair_type']);
			$type['room_address'] = $l['room_address'];
			$type['id'] = $l['id'];
			$type['repairinfo'] = $l['repairinfo'];
			$type['image'] = $l['image'];
			$type['status'] = $l['status'];
			$type['time_repair'] = $l['time_repair'];
			$type['time_thedoor'] = $l['time_thedoor'];
			$type['time_solve'] = $l['time_solve'];
			$type['order_id'] = $l['order_id'];
			$lis[] = $type;
		}
			
		}else{
			$lis = 1;
		}
		
        return json_encode($lis);

    }
    //投诉建议
    public function submits()
    {
        //获取表单数据
        
        $data=request()->post();
        //Log::write($data["user_id"],"posolsal");
        $data['time'] = date('Y-m-d H:i:s',time());
		$data['order_id'] = time().rand(100000,999999);
        $roominfo=Db::table("roominfo")
                    ->where("community_id",$data["community_id"])
                    ->where("zz_group",$data['group'])
                    ->where("building",$data['building'])
                    ->where("unit",$data['unit'])
                    ->where("room",$data['room'])
                    ->find();
        //插入数据到数据库
		unset($data['group']);
        unset($data['building']);
        unset($data['unit']);
        unset($data['room']);
        $data["room_address"]=$roominfo["address"];
        $data["room_id"]=$roominfo["id"];
        $data['community_name'] = (new repairService())->communityIdName($data["community_id"]);
        $result = (new repairService())->proposalAdd($data);
        if(!empty($result)){
            //根据ID查询报修信息
            $proposalidlist = (new repairService())->proposalIdList($result);
            //根据小区ID查询打印机信息
            $communityidinfo = (new repairService())->communityIdInfo($proposalidlist['community_id']);
            $machineCode = $communityidinfo['machine_code'];
            $community = $communityidinfo['name'];
            
            //根据报修类型ID查询报修
            if($proposalidlist['type'] == 1){
                $type = '投诉';
            }elseif($proposalidlist['type'] == 2){
                $type = '建议';
            }elseif($proposalidlist['type'] == 3){
                $type = '表扬';
            }else{
                $type = '';
            }
            $contents = $proposalidlist['content'];
            $time = $proposalidlist['time'];
            //$printing = (new printDemo())->proposalPrinting($machineCode,$community,$type,$contents,$time);
           return json_encode('提交成功');
        }else{
            return json_encode('提交失败');
        }

    }
	  //提交个人报修信息
    public function complaint()
    {
		$data=request()->post();
        //Log::write($data,"complaint");
        //查询房屋
        $roominfo=Db::table("roominfo")
                    ->where("community_id",$data["community_id"])
                    ->where("zz_group",$data['group'])
                    ->where("building",$data['building'])
                    ->where("unit",$data['unit'])
                    ->where("room",$data['room'])
                    ->find();

        $data['room_address'] = $roominfo["address"];
        $data['out_room_id'] = $roominfo["out_room_id"];
        $data['time_repair'] = date('Y-m-d H:i:s',time());
        $data['status'] = 2;
		$data['order_id'] = time().rand(100000,999999);
        unset($data['group']);
        unset($data['building']);
        unset($data['unit']);
        unset($data['room']);
       
         $result = (new repairService())->repairAdd($data);
       
        if($result){
			return json_encode('OK');
            //根据ID查询报修信息
            $repairidlist = (new repairService())->repairIdList($result);
            //根据小区ID查询打印机信息
            $communityidinfo = (new repairService())->communityIdInfo($repairidlist['community_id']);
            $machineCode = $communityidinfo['machine_code'];
            $community = $communityidinfo['name'];
            $room = $repairidlist['room_address'];
            $people = $repairidlist['people'];
            $phone = $repairidlist['phone'];
            //根据报修类型ID查询报修
            $repair_type= (new repairService())->typeIdName($repairidlist['repair_type']);
            $repairinfo = $repairidlist['repairinfo'];
            $time_thedoor = $repairidlist['time_thedoor'];
            $time_repair = $repairidlist['time_repair'];
            //$printing = (new printDemo())->repairPrinting($machineCode,$community,$room,$people,$phone,$repair_type,$repairinfo,$time_thedoor,$time_repair);
            return json_encode('OK');
        }else{
            return json_encode('no');
        }
    }
    //用户投诉建议记录
    public function complaintlists()
    {
        $user_id = $_GET['user_id'];
        $list = (new xcxService())->complaintlist($user_id);
		return json_encode($list);
    }
 //小区公告列表
    public function notice()
    {
       $user_id = $_GET['user_id'];
        $user = (new xcxService())->user($user_id);
        if ($user){
            $communityId = $user['community_id'];
			$notice['name'] = (new xcxService())->communityNotice($communityId);
            $notice = (new xcxService())->notice($communityId);
			if($notice){
				 return json_encode($notice);
			}else{
				 return json_encode(1);
			}
        }else{
            return json_encode(0);
        }
        return json_encode($notice);
    }
	
    //图片上传
    public function upload()
    {
		 $file = request()->file('file');
		  if ($file) {
		   $info = $file->move('uploads');
		   if($info){
			$file = $info->getSaveName();
			$file = str_replace('\\', '/', $file);
			$image = "https://www.jfzhiwen.com/uploads/".$file;
			return $image;
		   }
		  }
  
    }

  
	//到家服务
	public function homeServe()
    {
		$address = 'C:\phpStudy\WWW\zzkj\public\license\\'.'notice'.time().rand(100000,999999).'.txt';//文本路径
        file_put_contents($address,file_get_contents("php://input"),FILE_APPEND);//将数据读入文本
        $data = json_decode(file_get_contents($address),true);//读取文本并变成数组
        //查询房屋
        $data['room_address'] = $data['group'].$data['building'].'幢'.$data['unit'].'单元'.$data['room'].'室';
        $data['time_repair'] = date('Y-m-d H:i:s',time());//添加时间
        $data['status'] = 2;
		$data['order_id'] = time().rand(100000,999999);
        unset($data['group']);
        unset($data['building']);
        unset($data['unit']);
        unset($data['room']);
        //插入数据到数据库
         $result = (new xcxService())->homeServe($data);
        if($result){
			
            //根据ID查询报修信息
            $repairidlist = (new homeService())->repairIdList($result);
            //根据小区ID查询打印机信息
            $communityidinfo = (new homeService())->communityIdInfo($repairidlist['community_id']);
            $machineCode = $communityidinfo['machine_code'];
            $community = $communityidinfo['name'];
            $room = $repairidlist['room_address'];
            $people = $repairidlist['people'];
            $phone = $repairidlist['phone'];
			$money = $repairidlist['money'];
            //根据报修类型ID查询报修
            $repair_type= (new homeService())->typeIdName($repairidlist['repair_type']);
            $repairinfo = $repairidlist['repairinfo'];
            $time_thedoor = $repairidlist['time_thedoor'];
            $time_repair = $repairidlist['time_repair'];
            $printing = (new printDemo())->homePrinting($machineCode,$community,$room,$people,$phone,$repair_type,$repairinfo,$time_thedoor,$time_repair,$money);
           
		   return json_encode('OK');
        }else{
            return json_encode('no');
        }
    }
	 //用户到家
    public function homelists()
    {
        $user_id = $_GET['user_id'];
        $list = (new xcxService())->repairslist($user_id);
		foreach($list as $l){
			$type['name'] = (new xcxService())->repairsName($l['repair_type']);
			$type['room_address'] = $l['room_address'];
			$type['id'] = $l['id'];
			$type['repairinfo'] = $l['repairinfo'];
			$type['image'] = $l['image'];
			$type['status'] = $l['status'];
			$type['time_repair'] = $l['time_repair'];
			$type['time_thedoor'] = $l['time_thedoor'];
			$type['time_solve'] = $l['time_solve'];
			$type['order_id'] = $l['order_id'];
			$lis[] = $type;
		}
        return json_encode($lis);
    }
	//服务类型
	public function homeperson()
    {
        $repairType = (new xcxService())->hometypeList();
        return json_encode($repairType);
    }
	//绑定房屋
	public function addroom()
	{
		$data=request()->post();
        //Log::write($data,"addroom");
        $data['time'] = date('Y-m-d H:i:s',time());
		

		$roominfo=Db::table("roominfo")
                    ->where("community_id",$data["community_id"])
                    ->where("zz_group",$data['group'])
                    ->where("building",$data['building'])
                    ->where("unit",$data['unit'])
                    ->where("room",$data['room'])
                    ->find();
        if(empty($roominfo)){
            return '2';
        }
        $issetroom=Db::table('room')->where('user_id',$data['user_id'])->find();
        if($issetroom)
        {
            return "4";//
        }
        
        $issetss = (new xcxService())->roomsel($roominfo["id"],$data['user_id']);
		if($issetss)
		{
			return "3";//用户已添加该房间
		}
        $data["address"]=$roominfo["address"];
        $data["room_id"]=$roominfo["id"];
        //插入数据到数据库
        $result = (new xcxService())->proposalAdd($data);
		if($result){
			return '1';
		}else{
			return '2';
		}
	}
	//用户历史帐单
	public function billList()
	{
		$user_id = $_GET['user_id'];
        $userroom=Db::table('room')->where('user_id',$user_id)->find();
        if(empty($userroom))
        {
            return json_encode(0);
        }else{
            $roominfo=Db::table('roominfo')->where('id',$userroom["room_id"])->find();
            $result =Db::name('bill')->where('out_room_id',$roominfo["out_room_id"])->where('status','TRADE_SUCCESS')->order('id desc')->select()->toArray();
            return json_encode($result);
        }
		/*$result = (new xcxService())->billList($user_id);
		if($result){
			return json_encode($result);
		}else{
			return json_encode(0);
		}*/
		
		
	}
	//用户绑定的房屋信息
	public function roomlist()
	{
		$user_id = $_GET['user_id'];
		$result = (new xcxService())->roomList1($user_id);
		return json_encode($result);
	}
	//删除用户绑定的房屋信息
	public function delroom()
	{
		$id = $_GET['id'];
		$result = (new xcxService())->delroom($id);
		return json_encode(1);
	}
	
    public function getuserroom(){
        $user_id=request()->get("user_id");
        $roominfo=Db::table("room")->where("user_id",$user_id)->find();
        if(empty($roominfo)){
            return json(['errorCode'=>'1','error' => '您还没有添加房屋,请先添加房屋']);
        }else{
            $communityinfo=Db::table("community")->where("community_id",$roominfo["community_id"])->find();
            $roominfo["community_name"]=$communityinfo["community_name"];
            return json_encode($roominfo);
        }
    }
	
    public function getphone(){
        $user_id=request()->get("user_id");
        $roominfo=Db::table("room")->where("user_id",$user_id)->find();
        if(empty($roominfo)){
            return json(['errorCode'=>'1','error' => '您还没有添加房屋,请先添加房屋']);
        }else{
            $communityinfo=Db::table("community")->where("community_id",$roominfo["community_id"])->find();
            
            //$phone= Db::name('property')->where('id',$communityinfo["property_id"])->value('hotline');
            $roominfo["community_name"]=$communityinfo["community_name"];
            $roominfo["phone"]=$communityinfo["hotline"];
            return json_encode($roominfo);
        }
    }

}